// users.service.ts
import { Injectable, Logger, ConflictException } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { User } from './users.entity';

@Injectable()
export class UserService {
  private readonly logger = new Logger(UserService.name);

  constructor(
    @InjectRepository(User)
    private usersRepository: Repository<User>,
  ) {}

  // 根据手机号查找用户
  async findByPhone(phone: string): Promise<User | null> {
    this.logger.log(`根据手机号查找用户: ${phone}`);
    const user = await this.usersRepository.findOne({ where: { phone } });
    this.logger.log(`查找结果: ${user ? '找到用户' : '未找到用户'}`);
    return user;
  }

  // 根据邮箱查找用户
  async findByEmail(email: string): Promise<User | null> {
    this.logger.log(`根据邮箱查找用户: ${email}`);
    const user = await this.usersRepository.findOne({ where: { email } });
    this.logger.log(`查找结果: ${user ? '找到用户' : '未找到用户'}`);
    return user;
  }

  // 根据Facebook ID查找用户
  async findByFacebookId(facebookId: string): Promise<User | null> {
    this.logger.log(`根据Facebook ID查找用户: ${facebookId}`);
    const user = await this.usersRepository.findOne({ where: { facebookId } });
    this.logger.log(`查找结果: ${user ? '找到用户' : '未找到用户'}`);
    return user;
  }

  // 根据WeChat ID查找用户
  async findByWechatId(wechatId: string): Promise<User | null> {
    this.logger.log(`根据WeChat ID查找用户: ${wechatId}`);
    const user = await this.usersRepository.findOne({ where: { wechatId } });
    this.logger.log(`查找结果: ${user ? '找到用户' : '未找到用户'}`);
    return user;
  }

  // 根据ID查找用户
  async findById(id: number): Promise<User | null> {
    this.logger.log(`根据ID查找用户: ${id}`);
    const user = await this.usersRepository.findOne({ where: { id } });
    this.logger.log(`查找结果: ${user ? '找到用户' : '未找到用户'}`);
    return user;
  }

  // 创建普通用户
  async createUser(
    phone: string,
    password: string,
    name: string,
  ): Promise<Omit<User, 'password'>> {
    this.logger.log(`创建用户，手机号: ${phone}`);
    const existingUser = await this.findByPhone(phone);
    if (existingUser) {
      throw new ConflictException('用户已存在');
    }

    const user = this.usersRepository.create({
      phone,
      password,
      name,
    });

    const savedUser = await this.usersRepository.save(user);
    this.logger.log(`用户创建成功，用户ID: ${savedUser.id}`);
    const { password: _, ...result } = savedUser;
    return result;
  }

  // 创建Google用户
  async createGoogleUser(userData: {
    email: string;
    name: string;
    googleId: string;
    avatar: string;
    password: string;
  }): Promise<Omit<User, 'password'>> {
    this.logger.log(`创建Google用户，邮箱: ${userData.email}`);

    // 检查用户是否已存在
    const existingUser = await this.findByEmail(userData.email);
    if (existingUser) {
      throw new ConflictException('用户已存在');
    }

    const user = this.usersRepository.create({
      email: userData.email,
      name: userData.name,
      googleId: userData.googleId,
      avatar: userData.avatar,
      // 为Google用户设置一个默认密码
      password: userData.password || 'GOOGLE_AUTH',
    });

    const savedUser = await this.usersRepository.save(user);
    this.logger.log(`Google用户创建成功，用户ID: ${savedUser.id}`);
    const { password: _, ...result } = savedUser;
    return result;
  }

  // 创建Facebook用户
  async createFacebookUser(userData: {
    facebookId: string;
    email: string;
    name: string;
    avatar: string;
    password: string;
  }): Promise<Omit<User, 'password'>> {
    this.logger.log(`创建Facebook用户，Facebook ID: ${userData.facebookId}`);

    // 检查用户是否已存在
    const existingUser = await this.findByFacebookId(userData.facebookId);
    if (existingUser) {
      throw new ConflictException('用户已存在');
    }

    const user = this.usersRepository.create({
      facebookId: userData.facebookId,
      email: userData.email,
      name: userData.name,
      avatar: userData.avatar,
      // 为Facebook用户设置一个默认密码
      password: userData.password || 'FACEBOOK_AUTH',
    });

    const savedUser = await this.usersRepository.save(user);
    this.logger.log(`Facebook用户创建成功，用户ID: ${savedUser.id}`);
    const { password: _, ...result } = savedUser;
    return result;
  }

  // 创建WeChat用户
  async createWechatUser(userData: {
    wechatId: string;
    name: string;
    gender: string;
    avatar: string;
    password: string;
  }): Promise<Omit<User, 'password'>> {
    this.logger.log(`创建WeChat用户，WeChat ID: ${userData.wechatId}`);

    // 检查用户是否已存在
    const existingUser = await this.findByWechatId(userData.wechatId);
    if (existingUser) {
      throw new ConflictException('用户已存在');
    }

    const user = this.usersRepository.create({
      wechatId: userData.wechatId,
      name: userData.name,
      gender: userData.gender,
      avatar: userData.avatar,
      // 为WeChat用户设置一个默认密码
      password: userData.password || 'WECHAT_AUTH',
    });

    const savedUser = await this.usersRepository.save(user);
    this.logger.log(`WeChat用户创建成功，用户ID: ${savedUser.id}`);
    const { password: _, ...result } = savedUser;
    return result;
  }

  // 更新用户Google信息
  async updateUserGoogleInfo(
    userId: number,
    updateData: { googleId: string; avatar: string },
  ): Promise<void> {
    this.logger.log(`更新用户Google信息，用户ID: ${userId}`);
    await this.usersRepository.update(userId, {
      googleId: updateData.googleId,
      avatar: updateData.avatar,
    });
  }

  // 根据ID查找用户(不包含密码)
  async findUserWithoutPasswordById(
    id: number,
  ): Promise<Omit<User, 'password'> | null> {
    this.logger.log(`根据ID查找用户(不包含密码): ${id}`);
    const user = await this.usersRepository.findOne({ where: { id } });
    if (!user) {
      return null;
    }
    const { password: _, ...result } = user;
    return result;
  }

  // 更新用户位置信息
  async updateUserLocation(
    userId: number,
    latitude: number,
    longitude: number,
    location: string,
    // 添加额外的地理位置信息参数
    locationDetails?: {
      country?: string;
      province?: string;
      city?: string;
      district?: string;
      source?: 'amap' | 'google'; // 标记位置信息来源
    },
  ): Promise<void> {
    this.logger.log(`更新用户位置信息，用户ID: ${userId}`);
    // 构建更新数据对象
    const updateData: any = {
      latitude,
      longitude,
      location,
    };

    // 如果提供了详细的位置信息，则更新用户的from字段（国籍信息）
    // 即使只有部分信息也更新，而不是只在country存在时才更新
    if (
      locationDetails &&
      (locationDetails.country ||
        locationDetails.province ||
        locationDetails.city)
    ) {
      updateData.from = `${locationDetails.country || ''}${locationDetails.province ? ', ' + locationDetails.province : ''}${locationDetails.city ? ', ' + locationDetails.city : ''}`;
    }

    await this.usersRepository.update(userId, updateData);
  }

  // 更新用户资料
  async updateUserProfile(
    userId: number,
    profileData: Partial<User>,
  ): Promise<Omit<User, 'password'> | null> {
    this.logger.log(`更新用户资料，用户ID: ${userId}`);

    // 移除密码字段以防止意外更新
    const { password, ...updateData } = profileData;

    // 特别处理 birthday 字段，确保它是有效的日期对象或 null
    if (updateData.birthday) {
      if (typeof updateData.birthday === 'string') {
        // 如果是字符串，尝试转换为日期对象
        const date = new Date(updateData.birthday);
        if (isNaN(date.getTime())) {
          // 如果不是有效日期，设置为 null
          updateData.birthday = null;
        } else {
          updateData.birthday = date;
        }
      } else if (!(updateData.birthday instanceof Date)) {
        // 如果既不是字符串也不是日期对象，设置为 null
        updateData.birthday = null;
      }
    }

    await this.usersRepository.update(userId, updateData);
    const updatedUser = await this.findUserWithoutPasswordById(userId);
    return updatedUser;
  }

  // 增加用户粉钻
  async addDiamonds(userId: number, amount: number): Promise<void> {
    this.logger.log(`增加用户粉钻，用户ID: ${userId}，数量: ${amount}`);
    await this.usersRepository
      .createQueryBuilder()
      .update(User)
      .set({ diamonds: () => `diamonds + ${amount}` })
      .where('id = :userId', { userId })
      .execute();
  }

  // 减少用户粉钻
  async deductDiamonds(userId: number, amount: number): Promise<void> {
    this.logger.log(`减少用户粉钻，用户ID: ${userId}，数量: ${amount}`);
    await this.usersRepository
      .createQueryBuilder()
      .update(User)
      .set({ diamonds: () => `diamonds - ${amount}` })
      .where('id = :userId', { userId })
      .andWhere('diamonds >= :amount', { amount })
      .execute();
  }

  // 设置用户VIP状态
  async setVipStatus(
    userId: number,
    isVip: boolean,
    vipEndTime?: Date,
  ): Promise<void> {
    this.logger.log(`设置用户VIP状态，用户ID: ${userId}，VIP: ${isVip}`);
    // 如果设置了结束时间，需要检查是否已过期
    const effectiveIsVip = vipEndTime
      ? isVip && new Date(vipEndTime) > new Date()
      : isVip;
    await this.usersRepository.update(userId, {
      isVip: effectiveIsVip,
      vipEndTime,
    });
  }

  // 根据国籍查找用户
  async findUsersByNationality(nationality: string): Promise<User[]> {
    this.logger.log(`根据国籍查找用户: ${nationality}`);
    const users = await this.usersRepository
      .createQueryBuilder('user')
      .where('user.from LIKE :nationality', { nationality: `%${nationality}%` })
      .getMany();
    return users;
  }
}
